#include "../include/http_server.h"
#include "../include/db_manager.h"
#include "../include/user_manager.h"
#include "../include/search_engine.h"
#include "../include/ai_integration.h"
#include "../include/config.h"
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>

int main(int argc, char* argv[]) {
    // Load configuration file
    Config& config = Config::getInstance();
    std::string config_file = "config.ini";
    if (argc > 1) {
        config_file = argv[1];
    }
    
    if (!config.loadFromFile(config_file)) {
        std::cout << "Warning: Unable to load configuration file, using default configuration" << std::endl;
    }
    
    // Create database manager instance
    std::unique_ptr<DBManager> db_manager = std::make_unique<DBManager>();
    
    // Initialize database
    if (!db_manager->initialize(config.getDatabasePath())) {
        std::cerr << "Database initialization failed" << std::endl;
        return 1;
    }
    
    // Create user manager instance
    std::unique_ptr<UserManager> user_manager = std::make_unique<UserManager>();
    
    // Create search engine instance
    std::unique_ptr<SearchEngine> search_engine = std::make_unique<SearchEngine>();
    
    // Create AI integration instance
    std::unique_ptr<AIIntegration> ai_integration = std::make_unique<AIIntegration>();
    
    // Initialize AI integration
    std::string deepseek_api_key = config.getDeepSeekAPIKey();
    
    // Even without API key, initialize in mock mode for demo purposes
    if (!ai_integration->initialize(deepseek_api_key, config.getDeepSeekBaseURL())) {
        std::cout << "Warning: AI integration initialization failed, AI features will be unavailable" << std::endl;
    } else {
        std::cout << "AI integration initialized successfully" << std::endl;
        ai_integration->setSystemPrompt(config.getAISystemPrompt());
        
        if (deepseek_api_key.empty()) {
            std::cout << "Note: Running in mock AI mode (no API key provided). Will return simulated responses." << std::endl;
        }
    }
    
    // Create HTTP server instance
    HttpServer server(config.getServerPort());
    
    // Set managers
    server.setDatabaseManager(db_manager.get());
    server.setUserManager(user_manager.get());
    server.setSearchEngine(search_engine.get());
    server.setAIIntegration(ai_integration.get());
    
    // Start server
    if (!server.start()) {
        std::cerr << "Server startup failed" << std::endl;
        return 1;
    }
    
    std::cout << "Server started on port " << config.getServerPort() << ", press Ctrl+C to stop..." << std::endl;
    std::cout << "Visit http://localhost:" << config.getServerPort() << " to view the application" << std::endl;
    
    // Keep program running
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    
    // Stop server
    server.stop();
    
    return 0;
}